<!DOCTYPE HTML>
<html>

<head>
   <title>table对象</title>
   <meta charset="utf-8" />
   <style>
      table {
         width: 600px;
         border-collapse: collapse;
         text-align: center;
      }

      td,
      th {
         border: 1px solid #ccc
      }

      thead td {
         font-weight: bold;
      }

      .ml2 {
         margin-left: 1rem;
      }
   </style>

</head>

<body>

   <h3>Table对象</h3>
   <div class="ml2">
      <div>常用属性: rows ------------>table.rows</div>
      <div>常用方法:</div>
      <div>1. insertRow(index) 创建并添加, index 可省略</div>
      <div>2. deleteRow(index) </div>
      <div>3. createTHead()</div>
      <div>4. createTBody()</div>
   </div>


   <h3>TableRow 对象</h3>
   <div class="ml2">
      <div>常用属性: </div>
      <div>1.cells</div>
      <div>2.innerHTML</div>
      <div>3.rowIndex</div>
      <div>常用方法:</div>
      <div>1.insertCell(index) //返回TableCell对象</div>
      <div>2.deleteCell(index) </div>
   </div>

   <h3>TableCell 对象</h3>
   <div class="ml2">
      <div>常用属性: </div>
      <div>1.cellIndex</div>
      <div>2.innerHTML</div>
      <div>3.colSpan</div>
      <div>3.rowSpan</div>
   </div>


   <table id="t1">

   </table>

   <script>
      var col = 4;
      var table = document.getElementById("t1");
      //1.createTHead,创建thead元素,并追加到table下
      var thead = table.createTHead();
      //2.insertRow,创建tr,并追加
      var tr = thead.insertRow();
      for (var i = 0; i < col; i++) {
         //3.insertCell, 创建td,并追加
         var td = tr.insertCell();
         td.innerHTML = i + "th";
         if (i == 3) {
            td.innerHTML = "删除";
         }
      }
      //4.createTBody,创建tbody元素,并追加到table下
      var tbody = table.createTBody();

      for (var i = 0; i < 5; i++) {
         var tr = tbody.insertRow();
         for (var j = 0; j < col; j++) {
            var td = tr.insertCell();
            td.innerHTML = (i + 1) * (j + 1) + "td";
            if (j == col - 1) {
               td.innerHTML = ""
               var btn = document.createElement("button");
               btn.innerHTML = "x"
               td.appendChild(btn);
               btn.onclick = function () {
                  var tr = this.parentNode.parentNode;
                  if (confirm(`确认要删除${tr.rowIndex}吗?`)) {
                     //5.deleteRow(tr.rowIndex)删除行
                     table.deleteRow(tr.rowIndex);
                  } else {
                     console.log("你没有删除这一行");
                  }
               }
            }
         }
      }


      console.log("cells====", table.rows[0].cells);
      console.log("cellIndex====", table.rows[0].cells[0].cellIndex);
      console.log("innerHTML====", table.rows[0].cells[0].innerHTML);
      console.log("colSpan====", table.rows[0].cells[0].colSpan);
      console.log("rowSpan====", table.rows[0].cells[0].rowSpan);
   </script>
</body>

</html>